package edu.vt.sdm.tcga.filenavigator.view;

import java.util.Hashtable;

import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;

import edu.vt.sdm.tcga.filenavigator.model.FileBean;

public class LabelContentProvider implements ILabelProvider{


	// Cached Icons
	private Hashtable<Program, Image> iconCache = new Hashtable<Program, Image>();
	
	@Override
	public Image getImage(Object element) {
		FileBean file = (FileBean)element;
		String nameString = file.toString();
		Image image = null;
		
		int dot = nameString.lastIndexOf('.');
		
		// Get the icon from the file system
		if(dot != -1){
			// Find the program using the file extensions
			String extension = nameString.substring(dot);
			Program program = Program.findProgram(extension);
			
			// Get the icon based on the extension
			if(program != null){
				image = getIconFromProgram(program);
			}
		}
		
		if(image == null){
			image = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);
		}
		
		return file.isDirectory() ? 
				PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER) : 
				image;
	}

	@Override
	public String getText(Object element) {
		return element.toString();
	}

	@Override
	public void addListener(ILabelProviderListener arg0) {
	}

	@Override
	public void dispose() {
	}

	@Override
	public boolean isLabelProperty(Object arg0, String arg1) {
		return false;
	}

	@Override
	public void removeListener(ILabelProviderListener arg0) {
	}

	public Image getIconFromProgram(Program program){
		Image image = (Image)iconCache.get(program);
		
		if(image == null){
			ImageData imageData = program.getImageData();
			
			if(imageData != null){
				image = new Image(Display.getCurrent(), imageData);
				iconCache.put(program, image);
			}
		}
		
		return image;
	}
}
